// https://leetcode.cn/problems/lru-cache/

class BiNode {
public:
    int key;
    int val;
    BiNode* pre;
    BiNode* next;
    BiNode(int key, int val) {
        this->key = key;
        this->val = val;
        pre = next = NULL;
    }    
};
class LRUCache {
public:
    int capacity;
    int size;
    BiNode* head;
    BiNode* tail;
    unordered_map<int, BiNode*> rec;
    LRUCache(int capacity) {
        this->size = 0;
        this->capacity = capacity;
        head = new BiNode(-1, -1);
        tail = new BiNode(-1, -1);
        head->next = tail;
        tail->pre = head;
    }
    
    int get(int key) {
        if (rec.find(key) == rec.end()) return -1;
        moveToHead(rec[key]);
        return rec[key]->val;
    }
    
    void put(int key, int value) {
        if (rec.find(key) == rec.end()) {
            BiNode* node = new BiNode(key, value);
            rec[key] = node;
            addToHead(node); 
            size++;
            if (size > capacity) {
                BiNode* tmp = removeTail();
                rec.erase(tmp->key);
                delete tmp;
                --size;
            }
        } else {
            BiNode* node = rec[key];
            node->val = value;
            moveToHead(node);
        }
    }
    void addToHead(BiNode* node) {
        node->next = head->next;
        head->next->pre = node;
        head->next = node;
        node->pre = head;
    }
    void removeNode(BiNode* node) {
        BiNode* tmp = node->pre;
        tmp->next = node->next;
        node->next->pre = tmp;
        // rec.erase(node->val);
        // delete node;
    }    
    void moveToHead(BiNode* node) {
        removeNode(node);
        addToHead(node);
    }
    BiNode* removeTail() {
        BiNode* tmp = tail->pre;
        removeNode(tmp);
        return tmp;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */